﻿using ShiQuan.LogHelper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace ShiQuan.RdpDesktop
{
    /// <summary>
    /// 数据加密、解密辅助
    /// </summary>
    public class ProtectedHelper
    {
        /// <summary>
        /// 密码因子
        /// </summary>
        static byte[] s_aditionalEntropy = null;
        /// <summary>
        /// 加密方法
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static byte[] Protect(byte[] data)
        {
            try
            {
                //调用System.Security.dll
                return ProtectedData.Protect(data, s_aditionalEntropy, DataProtectionScope.LocalMachine);
            }
            catch (CryptographicException e)
            {
                var info = "Data was not encrypted. An error occurred.\n" + e.ToString();
                Console.WriteLine(info);
                Logger.Error("加密数据异常", info);
                return null;
            }
        }

        /// <summary>
        /// 解密方法
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static byte[] Unprotect(byte[] data)
        {
            try
            {
                //Decrypt the data using DataProtectionScope.CurrentUser.
                return ProtectedData.Unprotect(data, s_aditionalEntropy, DataProtectionScope.LocalMachine);
            }
            catch (CryptographicException e)
            {
                Console.WriteLine("Data was not decrypted. An error occurred.");
                Console.WriteLine(e.ToString());
                return null;
            }
        }
    }
}
